﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace WinApp.Common
{
    public class TcpConnection
    {
        public DateTime LastConnectTime { get; set; }

        public TcpClient TcpClient { get; private set; }

        public Action<TcpClient, string> OnReceived;

        public TcpConnection(TcpClient tcpClient)
        {
            this.TcpClient = tcpClient;
        }

        public void HandleResponse()
        {
            try
            {
                string receivedData = Receive();

                string dataToSend = "Reply to: " + receivedData;
                Send(dataToSend);
            }
            catch
            {
                this.TcpClient.Close();                
            }
        }

        private void Send(string dataToSend)
        {
            if (string.IsNullOrEmpty(dataToSend))
            {
                return;
            }

            NetworkStream stream = this.TcpClient.GetStream();
            if (stream.CanWrite)
            {
                byte[] buffer = Encoding.UTF8.GetBytes(dataToSend);
                stream.Write(buffer, 0, buffer.Length);
            }
        }

        private string Receive()
        {
            string data = string.Empty;            
            NetworkStream stream = this.TcpClient.GetStream();            

            if (stream.CanRead)
            {
                StringBuilder sb = new StringBuilder();
                byte[] buffer = new byte[this.TcpClient.ReceiveBufferSize];
                while (stream.DataAvailable)
                {
                    stream.Read(buffer, 0, this.TcpClient.ReceiveBufferSize);
                    sb.Append(Encoding.UTF8.GetString(buffer));
                }

                data = sb.ToString();
                if (OnReceived != null)
                {
                    OnReceived(this.TcpClient, data);
                }
            }

            return data;
        }
    }
}
